package com.zxc.gulimall.ware.service.impl;

import com.zxc.common.constant.WareConstant;
import com.zxc.common.utils.R;
import com.zxc.gulimall.ware.entity.PurchaseDetailEntity;
import com.zxc.gulimall.ware.entity.WareSkuEntity;
import com.zxc.gulimall.ware.feign.ProductFeignClient;
import com.zxc.gulimall.ware.service.PurchaseDetailService;
import com.zxc.gulimall.ware.service.WareSkuService;
import com.zxc.gulimall.ware.vo.DoneVo;
import com.zxc.gulimall.ware.vo.MergeVo;
import com.zxc.gulimall.ware.vo.PurchaseDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxc.common.utils.PageUtils;
import com.zxc.common.utils.Query;

import com.zxc.gulimall.ware.dao.PurchaseDao;
import com.zxc.gulimall.ware.entity.PurchaseEntity;
import com.zxc.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Autowired
    private ProductFeignClient productFeignClient;


    /*
     * 完成采购
     * {"id":3,"items":[{"itemId":4,"status":3,"reason":""},{"itemId":5,"status":4,"reason":"无货"}]}
     * */
    @Transactional
    @Override
    public void done(DoneVo doneVo) {
        //1、根据前端传输过来的采购单Id，修改指定采购单的状态
        Long purchaseId = doneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISHED.getCode());


        //2、改变采购需求的状态
        //如果有一个采购需求没有采购成功那么我们需要改变采购单的状态为 4（有异常）
        List<PurchaseDoneVo> purchaseDoneVoList = doneVo.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDoneVoList.stream().map(purchaseDoneVo -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(purchaseDoneVo.getItemId());
            purchaseDetailEntity.setStatus(purchaseDoneVo.getStatus());
            if (purchaseDetailEntity.getStatus() == WareConstant.PurchaseDetailEnum.BUYFAIL.getCode()){
                purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
            }
            //原因放在哪里？ TODO   purchaseDoneVo.getReason();
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntityList);

        //更新采购单状态
        this.updateById(purchaseEntity);

        //3、将成功采购的商品进行入库，增加库存
        //如果采购的商品的状态为3（采购成功），我们才能够增加库存
          //2）、我们需要知道商品Id，商品名称，仓库名称，还有库存数
        List<WareSkuEntity> wareSkuEntityList = purchaseDoneVoList.stream().map(purchaseDoneVo -> {
            //我们需要保存的仓库数据的实体类
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            //1)、首先我们需要根据采购需求Id查询到指定的数据  sku_id（商品Id） ware_id(仓库Id) sku_num(库存数)
            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(purchaseDoneVo.getItemId());
            wareSkuEntity.setSkuId(purchaseDetailEntity.getSkuId());
            wareSkuEntity.setWareId(purchaseDetailEntity.getWareId());
            wareSkuEntity.setStockLocked(0);
            //根据商品Id取得商品的详细信息   分两种情况 1、如果是系统智能化的库存生成的采购需求，那么我们不需要得到商品的商品详细信息
            //2、如果是我们需要添加什么新商品，仓库里没有该商品的信息的话，我们需要调用产品的微服务进行产品详细信息查询。
            R info = productFeignClient.info(purchaseDetailEntity.getSkuId());
            Map rMap = (Map) info.get("skuInfo");
            try {
                //调用服务成功，那么我们就需要存储商品的名称
                if (info.getCode() == 0) {
                    String skuName = (String) rMap.get("skuName");
                    wareSkuEntity.setSkuName(skuName);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            wareSkuEntity.setStock(purchaseDetailEntity.getSkuNum());
            //如果库存信息里面没有这个仓库这个商品的信息我们就需要新增信息，否则就只需要更新库存
            //1）、我们先在仓库里面查询有没有匹配的信息，我们就进行一个新增操作
            List<WareSkuEntity> wareSkuEntities = wareSkuService.list(new QueryWrapper<WareSkuEntity>().eq("ware_id",wareSkuEntity.getWareId()).eq("sku_id",wareSkuEntity.getSkuId()));
            if (wareSkuEntities == null || wareSkuEntities.size() == 0){
                //新增商品库存信息
                wareSkuService.save(wareSkuEntity);
            }else {
                //添加库存
                wareSkuService.addSkuStocks(wareSkuEntity.getWareId(),wareSkuEntity.getSkuId(),wareSkuEntity.getStock());
            }
            return wareSkuEntity;
        }).collect(Collectors.toList());


    }

    /*
    * ids --> 采购单Id
    * */
    @Transactional
    @Override
    public void received(List<Long> ids) {
        //1、确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(item -> {
            //我们需要的是被创建和已被分配的采购单
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATE.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item -> {
            //把需要改变状态的采购单改变状态
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        //2、改变采购单的状态
        this.updateBatchById(collect);

        //3、改变采购项的状态
        collect.forEach((item)->{
            List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> collect1 = purchaseDetailEntityList.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect1);
        });
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null){
            //如果没有传purchaseId那么我们需要创建一个采购单记录
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());//新建状态
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //确认采购单的状态是0,1   TODO 以及采购商品需求的状态为0,1才可以合并整单
        PurchaseEntity byId = this.getById(purchaseId);
        if (byId.getStatus() == WareConstant.PurchaseStatusEnum.CREATE.getCode() || byId.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()){
            List<Long> items = mergeVo.getItems();
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> collect = items.stream().map(i -> {
                //合并整单，就是把采购需求的状态改变，并且设置上采购单的Id
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(i);
                purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnum.ASSIGNED.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(collect);

            //修改采购单的更新时间
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseId);
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);
        }
    }

    @Override
    public PageUtils queryPageUnreceiveList(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

}